import { api } from '../api';
import type { AvatarGroup, Avatar, AvatarGroupType } from '../types/avatar';

// Avatar服务
class AvatarService {
  // 获取Avatar组列表
  async getAvatarGroups(): Promise<AvatarGroup[]> {
    const response = await api.get<{ rows: Record<string, unknown>[]; count: number }>(
      '/avatar-groups'
    );
    // 映射后端字段到前端AvatarGroup接口
    const groups: AvatarGroup[] = (response.rows || []).map(item => ({
      group_id: item.group_id as string,
      name: item.name as string,
      num_looks: item.num_looks as number,
      preview_image: item.preview_image as string,
      group_type: item.group_type as AvatarGroupType,
      created_at: item.created_at as number | undefined,
      account_id: item.account_id as number | undefined,
    }));
    return groups;
  }

  // 获取指定组中的Avatars
  async getAvatarsInGroup(groupId: string): Promise<Avatar[]> {
    const response = await api.get<{ rows: Record<string, unknown>[]; count: number }>(
      `/avatar-groups/${groupId}/avatars`
    );
    // 映射后端字段到前端Avatar接口
    const avatars: Avatar[] = (response.rows || []).map(item => ({
      avatar_id: item.avatar_id as string,
      name: (item.avatar_name || item.name) as string, // 后端字段名是 avatar_name
      preview_image: (item.preview_image_url || item.preview_image) as string, // 后端字段名是 preview_image_url
      group_id: item.group_id as string,
      account_id: item.account_id as number | undefined,
      default_voice_id: item.default_voice_id as string | undefined, // 映射默认语音ID
    }));
    return avatars;
  }

  // 获取Avatar详情
  async getAvatarDetail(avatarId: string): Promise<Avatar> {
    const response = await api.get<Avatar>(`/avatars/${avatarId}`);
    return response;
  }
}

export default new AvatarService();
